package com.bckj.fastboot.core.extra.license;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Linux服务器硬件信息获取
 */
public class LinuxServerInfos extends AbstractServerInfos {
    
    @Override
    protected List<String> getIpAddress() throws Exception {
        List<InetAddress> inetAddresses = getLocalAllInetAddress();
        if (inetAddresses != null && !inetAddresses.isEmpty()) {
            return inetAddresses.stream()
                    .map(InetAddress::getHostAddress)
                    .distinct()
                    .map(String::toLowerCase)
                    .collect(Collectors.toList());
        }
        return null;
    }
    
    @Override
    protected List<String> getMacAddress() throws Exception {
        List<InetAddress> inetAddresses = getLocalAllInetAddress();
        if (inetAddresses != null && !inetAddresses.isEmpty()) {
            return inetAddresses.stream()
                    .map(this::getMacByInetAddress)
                    .distinct()
                    .collect(Collectors.toList());
        }
        return null;
    }
    
    @Override
    protected String getCpuSerial() throws Exception {
        String serialNumber = "";
        // 使用dmidecode命令获取CPU序列号
        String[] shell = {"/bin/bash", "-c", "dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
        Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine();
        if (line != null) {
            serialNumber = line.trim();
        }
        reader.close();
        return serialNumber;
    }
    
    @Override
    protected String getMainBoardSerial() throws Exception {
        String serialNumber = "";
        // 使用dmidecode命令获取主板序列号
        String[] shell = {"/bin/bash", "-c", "dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};
        Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine();
        if (line != null) {
            serialNumber = line.trim();
        }
        reader.close();
        return serialNumber;
    }
}